package com.dmz.insclient.server;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.extra.ftp.Ftp;
import com.dmz.insclient.client.TcpClient;
import com.dmz.insclient.service.JieXiMes;
import com.dmz.insclient.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author lee
 */
@Slf4j
@Component
public class InsServer {

    // 监听端口，默认7111
    @Value("${csp.server.port}")
    private int cspServerPort;
    @Value("${sb.server.ip}")
    private String sbIp;
    @Value("${bps.server.ip}")
    private String bpsIp;
    @Value("${csp.server.ip1}")
    private String cspIp1;
    @Value("${csp.server.ip2}")
    private String cspIp2;
    @Value("${csp.server.ip3}")
    private String cspIp3;
    @Value("${csp.server.ip4}")
    private String cspIp4;
    @Value("${csp.server.ip5}")
    private String cspIp5;
    @Value("${csp.server.ip6}")
    private String cspIp6;
    @Value("${csp.server.ip7}")
    private String cspIp7;
    @Value("${csp.server.ip8}")
    private String cspIp8;
    @Value("${csp.server.ip9}")
    private String cspIp9;


    @Value("${bps.user.name}")
    private String userName1;
    @Value("${bps.user.passwd}")
    private String passwd1;

    @Value("${sm4.key}")
    private String key;

    @Value("${sm4.iv}")
    private String iv;

    private SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private ExecutorService threadPool;

    @PostConstruct
    public void init() {
        // 创建线程池
        threadPool = Executors.newFixedThreadPool(20); // 根据实际情况调整大小
    }

    /**
     * 启动监听Csp ServerSocket
     */
    public void startServer() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(cspServerPort);
            System.out.println(Charset.defaultCharset().displayName() + "TCP Server[" + cspServerPort + "]已经启动，开始监听......");
            log.info("TCP Server[{}]已经启动，开始监听......", cspServerPort);
            while (true) {
                Socket listenSocket = serverSocket.accept();
                listenSocket.setSoTimeout(35000);

                // 使用线程池处理每个连接
                threadPool.execute(() -> {
                    handleClientConnection(listenSocket);
                });
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }


    private void handleClientConnection(Socket listenSocket) {
        String ip = listenSocket.getInetAddress().toString();
        log.info(ip);
        try {
            // 批量文件就绪通知、重发请求、单笔结算、单笔结算冲正、余额查询、进展查询、系统连通性测试
            if (ip.contains(sbIp)) {
                log.info("server 接受到 【社保】 请求的时间：{}", sdf2.format(new Date()));
                log.info("");
                log.info("server 接受到 【社保】 请求：");

                // 这个函数中的代码出现异常不能影响socket服务器的继续运行
                try {
                    processSbRequest(listenSocket);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }

            }
            // 回盘文件就绪通知、系统连通性测试
            else if (ip.contains(bpsIp)) {
                log.info("server 接受到 【bps】 请求的时间：{}", sdf2.format(new Date()));
                log.info("接收到请求...");
                log.info("");
                log.info("server 接受到 【bps】 请求：");
                // 这个函数中的代码出现异常不能影响socket服务器的继续运行
                try {
                    Document docGenerated = processBpsRequest(listenSocket);
                } catch (Exception e) {
                    log.error(e.toString());
                }
            }
            // 日终文件通知、收支文件通知、中银E贷社保
            else if (ip.contains(cspIp1) || ip.contains(cspIp2) || ip.contains(cspIp3) || ip.contains(cspIp4) || ip.contains(cspIp5) || ip.contains(cspIp6) || ip.contains(cspIp7) || ip.contains(cspIp8) || ip.contains(cspIp9)) {
                log.info("server 接受到 【csp】 请求的时间：{}", sdf2.format(new Date()));
                log.info("接收到请求...");
                log.info("");
                log.info("server 接受到 【csp】 请求：");

                // 这个函数中的代码出现异常不能影响socket服务器的继续运行
                try {
                    processCspRequest(listenSocket);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            log.info("TCP server 结束处理：{}", sdf2.format(new Date()));
            log.info("TCP server 结束处理");
            log.info("");
        } catch (Exception e) {
            log.error("处理客户端连接异常: {}", e.getMessage(), e);
        } finally {
            // 确保关闭Socket
            if (!listenSocket.isClosed()) {
                try {
                    listenSocket.close();
                } catch (IOException e) {
                    log.error("关闭客户端Socket异常: {}", e.getMessage());
                }
            }
        }
    }


    // 分发社保发来的请求至不同的系统
    private void processSbRequest(Socket sbSocket) throws Exception {
        try {
            DataInputStream datain = new DataInputStream(sbSocket.getInputStream());
            BufferedInputStream remoteBin = new BufferedInputStream(sbSocket.getInputStream());
            int datalength = datain.readInt();
            log.info("接收到社保报文长度：" + datalength);
            /* socket工具模拟接收 */
            //byte[] recBuffer = new byte[2048];
            //remoteBin.read(recBuffer, 0,2048);
            //String sbMessage = new String(recBuffer,"GBK");
            /* 接收对端 */
            byte[] recBuffer = new byte[datalength];
            remoteBin.read(recBuffer, 0, datalength);
            String sbMessage = new String(recBuffer, AppValues.csn_U8);
            log.info("报文数据{}", sbMessage);
            BufferedOutputStream Out = null;
            try {
                Out = new BufferedOutputStream(sbSocket.getOutputStream());// 从输入流缓冲区中读取数据
                // BufferedReader In = new BufferedReader(new
                // InputStreamReader(sbSocket.getInputStream(),"UTF-8"));
                String retmessage = "";

                // 社保的实际报文部分
                String sbMessage1 = "";
                String[] strs = sbMessage.split(">");
                for (int i = 0; i < strs.length - 1; i++) {
                    sbMessage1 += strs[i].toString() + ">";
                }

                Document docRecieved1 = DocumentHelper.parseText(sbMessage1.trim());// 将xml字符串转成xml
                String keyType = "";
                String InstId = docRecieved1.getRootElement().element("GrpHdr").element("Sender").element("InstId").getText().toString();
                String InstId1 = InstId.substring(7, 10);
                keyType = InstId.substring(0, 4) + InstId1;

                // 报文签名部分进行验签
                String sbSign = sbMessage.substring(sbMessage.lastIndexOf(">") + 1).trim();
                boolean valiDateFlag = false;
                valiDateFlag = RsaUtil.validate(sbMessage1, HexUtil.decodeHex(sbSign.toCharArray()), keyType);

                log.info("验证签名状态: {}", valiDateFlag);
                if (sbMessage1.length() > 4) {// 长度判断
                    Document docRecieved = DocumentHelper.parseText(sbMessage1.trim());// 将xml字符串转成xml
                    String tranType = docRecieved.getRootElement().element("GrpHdr").element("BusCd").getText().toString();
                    Document docGenerated = XmlUtils.generateXmlHead(tranType);
                    docGenerated.getRootElement().element("GrpHdr").element("Ref").setText(docRecieved.getRootElement().element("GrpHdr").element("Ref").getText().toString());
                    docGenerated.getRootElement().element("GrpHdr").element("Dgst").setText(docRecieved.getRootElement().element("GrpHdr").element("Dgst").getText().toString());
                    docGenerated.getRootElement().element("GrpHdr").element("Sender").element("InstId").setText(docRecieved.getRootElement().element("GrpHdr").element("Recver").element("InstId").getText().toString());
                    docGenerated.getRootElement().element("GrpHdr").element("Recver").element("InstId").setText(docRecieved.getRootElement().element("GrpHdr").element("Sender").element("InstId").getText().toString());
                    log.info("Document处理===============1");
                    if (valiDateFlag) {
                        // 0112001单笔结算、0112002单笔结算冲正、0113005余额查询，0114001连通性测试；直接发csp不需要组xml包
                        //2024.12.10 新增0100002客户状态查询
                        if ("0112001".equals(tranType.trim()) || "0113005".equals(tranType.trim()) || "0114001".equals(tranType.trim()) || "0112002".equals(tranType.trim()) || "0100001".equals(tranType.trim()) || "0100002".equals(tranType.trim())) {
                            log.info("Document处理===============2");
                            retmessage = dealWithCsp(sbMessage1, tranType);
                        }
                        // 0114002批量文件就绪通知、0114003重发请求、0113007进展查询；需要组xml包，关键信息发送bps
                        else if ("0114002".equals(tranType.trim()) || "0114003".equals(tranType.trim()) || "0113007".equals(tranType.trim())) {
                            log.info("Document处理===============3");
                            docGenerated = dealWithBps(docRecieved, docGenerated, tranType);
                            retmessage = XmlUtils.docToXml(docGenerated);
                        }
                        // 未知交易码直接返回
                        else {
                            log.info("Document处理===============4");
                            docGenerated.getRootElement().element("GrpHdr").element("Rst").element("Code").setText("9999");
                            docGenerated.getRootElement().element("GrpHdr").element("Rst").element("Info").setText("业务功能号未开通权限");
                            retmessage = XmlUtils.docToXml(docGenerated);
                        }
                    } else {// 验签失败直接返回
                        log.info("Document处理===============5");
                        docGenerated.getRootElement().element("GrpHdr").element("Rst").element("Code").setText("1014");
                        docGenerated.getRootElement().element("GrpHdr").element("Rst").element("Info").setText("报文验签失败");
                        retmessage = XmlUtils.docToXml(docGenerated);
                    }

                    // 对报文进行签名
                    log.info("Document处理===============6");
                    String overSign = RsaUtil.genValiInfo(retmessage.getBytes(AppValues.csn_U8), keyType);
                    retmessage = retmessage + overSign;
                    DataOutputStream dataout = null;
                    try{
                        log.info("Document处理===============7");
                        dataout = new DataOutputStream(sbSocket.getOutputStream());
                        byte[] data = retmessage.getBytes(AppValues.csn_U8);
                        if (data != null) {
                            dataout.writeInt(data.length);
                            // System.err.println(data.length);
                            String output = new String(data, AppValues.csn_U8);
                            log.info("返回报文为：\n {}", output);
                            dataout.write(data, 0, data.length);
                            dataout.flush();
                        }
                    }catch (Exception e) {
                        log.info("对报文进行签名 异常",e);
                        throw e;
                    }finally {
                        try {
                            if (dataout != null) {
                                dataout.close();
                            }
                        } catch (IOException e) {
                            log.error("关闭DataOutputStream时发生异常", e);
                        }

                    }
                }
            }catch (Exception e) {
                log.info("处理报文异常", e);
            }finally {
                try {
                    if (Out != null) {
                        Out.close();
                    }
                } catch (IOException e) {
                    log.error("关闭BufferedOutputStream时发生异常", e);
                }
            }
        } finally {
            try {
                if (sbSocket != null && !sbSocket.isClosed()) {
                    sbSocket.close();
                }
            } catch (IOException e) {
                log.error("关闭Socket时发生异常", e);
            }
        }
    }




    // 处理社保请求的具体业务逻辑。跟bps相关的额需要组xml报文：批量文件就绪通知、批量文件进展查询、批量文件重发请求
    public Document dealWithBps(Document docRecieved, Document docGenerated, String tranType) throws IOException {

//         String bpsUserName = GMUtil.db(key, iv, userName1);
//
//         String bpsUserPasswd = GMUtil.db(key, iv, passwd1);
        String bpsUserName = userName1;

        String bpsUserPasswd =  passwd1;
        log.info("dealWithBps处理===============1");
        TcpClient tcpClient = new TcpClient();
        // 接收公共报文头
        String Reference = docRecieved.getRootElement().element("GrpHdr").element("Ref").getText().toString().trim();
        String BusinessCode = docRecieved.getRootElement().element("GrpHdr").element("BusCd").getText().toString().trim();
        String TradeSource = docRecieved.getRootElement().element("GrpHdr").element("TradSrc").getText().toString().trim();
        String Sender = docRecieved.getRootElement().element("GrpHdr").element("Sender").element("InstId").getText().toString().trim();
        String Recver = docRecieved.getRootElement().element("GrpHdr").element("Recver").element("InstId").getText().toString().trim();
        String TransactionDate = docRecieved.getRootElement().element("GrpHdr").element("Date").getText().toString().trim();
        String TransactionTime = docRecieved.getRootElement().element("GrpHdr").element("Time").getText().toString().trim();
        String Resend = docRecieved.getRootElement().element("GrpHdr").element("Resend").getText().toString().trim();
        String Digest = docRecieved.getRootElement().element("GrpHdr").element("Dgst").getText().toString().trim();
        String SiSeqNo = docRecieved.getRootElement().element("BusiText").element("SiSeq").getText().toString().trim();
        String messageToBps = Reference + "|" + BusinessCode + "|" + TradeSource + "|" + Sender + "|" + Recver + "|" + TransactionDate + "|" + TransactionTime + "|" + Resend + "|" + Digest + "|" + SiSeqNo + "|";

        if (tranType.trim().equals("0114002")) {// 5.2.2批量文件就绪通知（社保发起）
            docGenerated.getRootElement().element("BusiText").element("SiSeq").setText(docRecieved.getRootElement().element("BusiText").element("SiSeq").getText().toString());
            docGenerated.getRootElement().element("BusiText").element("BkSeq").setText(docRecieved.getRootElement().element("BusiText").element("SiSeq").getText().toString() + "104");
            docGenerated.getRootElement().element("GrpHdr").element("Rst").element("Code").setText("0000");
            docGenerated.getRootElement().element("GrpHdr").element("Rst").element("Info").setText("已处理");
            log.info("dealWithBps处理===============2");
            String fileName = docRecieved.getRootElement().element("BusiText").element("FileName").getText().toString().trim();
            String fileSig = docRecieved.getRootElement().element("BusiText").element("FileSignMsg").getText().toString().trim();
            String fileMD5 = docRecieved.getRootElement().element("BusiText").element("FileMD5").getText().toString().trim();
            String insType = docRecieved.getRootElement().element("GrpHdr").element("Sender").element("InstId").getText().toString().trim().substring(7, 10);
            String insOrgCode = docRecieved.getRootElement().element("GrpHdr").element("Sender").element("InstId").getText().toString().trim().substring(0, 6);
            String SiSeq = docRecieved.getRootElement().element("BusiText").element("SiSeq").getText().toString().trim() + "104";
            String BkSeq = SiSeq + "104";
            String errFlag = "";// 前置处理标识，0成功，1失败
            String errMsg = "";// 前置处理错误信息，例如验签失败下载失败等
            String agentAct = "";// 对公账号
            String pch = "";// 批次号
            String jborg = "";// 经办机构号
            String flag = "";// 发放标识区分个人单位 0是个人 1是单位

            String InstId = docRecieved.getRootElement().element("GrpHdr").element("Sender").element("InstId").getText().toString();
            String keyType = insType;// 秘钥名称
            String remoterPath = "/" + insType; // sftp下载目录
            keyType = InstId.substring(0, 4) + insType;
            String path = File.separator +  "S" + keyType + "ToB104";
            String fileSavePath = EnvConfig.getProperty("file.save.path");
            String filePath = fileSavePath + keyType + File.separator;
            String ftpfilePath = "institution" + File.separator + insType + "";
            log.info("dealWithBps处理===============3");
            String keyPath = EnvConfig.getProperty("sftpKey.save.path");
            // 添加FTP
            boolean downloadFlag = SftpFileUtil.priKeyConnect(22, keyPath, "", path, filePath, fileName);
            log.info("dealWithBps处理===============4");
            if (downloadFlag) {

                log.info("下载文件：{} 完成", fileName);
                // 读取文件内容该为对文件求md5，对md5+文件名进行签名
                GzUtil.unGzipFile(filePath + fileName + ".gz");// 解压
                File f = FileUtil.newFile(filePath + fileName);
                Ftp ftp = new Ftp(bpsIp, 21, bpsUserName, bpsUserPasswd);
                try {
                    ftp.getClient().setFileType(FTP.BINARY_FILE_TYPE);
                    ftp.upload(ftpfilePath, f);
                    ftp.close();
                } catch (Exception e) {

                    log.error(e.getMessage(), e);
                }
                boolean valiDateFlag = false;
                File gzFile = FileUtil.newFile(filePath + fileName + ".gz");
                String filecontent = DigestUtil.md5Hex(FileUtils.file2byte(gzFile)) + fileName + ".gz";
                // filecontent =Md5Util.getMd5(filePath + fileName + ".gz") +
                // fileName+ ".gz";
                try {
                    log.info("dealWithBps处理===============5");
                    // 验证签名
                    // 测试验签
                    valiDateFlag = RsaUtil.validate(filecontent, HexUtil.decodeHex(fileSig.toCharArray()), keyType);
                    if (valiDateFlag) {
                        BufferedReader br1 = new BufferedReader(new FileReader(FileUtil.newFile(filePath + fileName)));
                        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(FileUtil.newFile(filePath + fileName)), "GBK"));
                        String tmpLine = "";
                        String w = "";
                        String org = "";

                        while ((w = br1.readLine()) != null) {
                            pch = w.substring(14, 34).trim();
                            log.info("批次号为：{}", pch);
                            break;
                        }
                        // 获取对公账号
                        if (br.readLine() != null) {
                            log.info("dealWithBps处理===============6");
                            if ((tmpLine = br.readLine()) != null) {
                                agentAct = new String(tmpLine.getBytes("GBK"), 355, 34, "GBK");
                                jborg = new String(tmpLine.getBytes("GBK"), 0, 6, "GBK");
                                flag = new String(tmpLine.getBytes("GBK"), 151, 1, "GBK");
                                log.info("对公账号为：" + agentAct);
                                log.info("经办机构为：" + jborg);
                                System.out.println("对公账号为：" + agentAct);
                            }
                        }
                        br.close();
                        if (agentAct.isEmpty()) {
                            errFlag = "1009";
                            errMsg = "对公账号为空！";
                            log.info("对公账号为空！");
                        } else {
                            errFlag = "0000";
                        }

                    } else if (filecontent.contains("系统找不到指定的路径")) {
                        errFlag = "1010";
                        errMsg = "文件不存在";
                        log.info("文件不存在！");
                        System.out.println("文件不存在！");
                    } else {
                        errFlag = "1011";
                        errMsg = "文件验签失败";
                        log.info("文件验签失败！");
                        System.out.println("文件验签失败！");
                    }

                } catch (Exception e1) {
                    log.error(e1.getMessage(), e1);
                }
            } else {
                errFlag = "1012";
                errMsg = "下载文件：" + fileName + " 失败";
                log.error("下载文件：{} 失败", fileName);
            }
            log.info("dealWithBps处理===============7");
            // 通知BPS系统
            messageToBps = messageToBps + fileName + "|" + fileMD5 + "|" + fileSig + "|" + agentAct.trim() + "|" + jborg + "|" + errFlag + "|" + errMsg + "|" + pch + "|" + flag + "|";
            try {
                String result = tcpClient.sendToBps(messageToBps, "0114002");//
                docGenerated.getRootElement().element("BusiText").element("Rst").element("Code").setText(result.split("\\|", -1)[0]);
                docGenerated.getRootElement().element("BusiText").element("Rst").element("Info").setText(result.split("\\|", -1)[1]);
                if (result.split("\\|", -1)[0].equals("0000")) {
                    // 短信通知业务部门--------------------------------------
                    if (result.split("\\|", -1)[2].equals("true")) {
                        //String TextMessage = "|" + fileName + "|" + insType + "|" + jborg.trim() + "|" + agentAct.trim()+ "|" + result.split("\\|", -1)[3] + "|" + result.split("\\|", -1)[4] + "|";
                        String TextMessage = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><MsgText><GrpHdr><BusCd>" + tranType + "</BusCd></GrpHdr><BusiText><FileName>" + fileName + "</FileName><insType>" + insType + "</insType><jborg>" + jborg.trim() + "</jborg><agentAct>" + agentAct.trim() + "</agentAct><phone>" + result.split("\\|", -1)[3] + "</phone><merchno>" + result.split("\\|", -1)[4] + "</merchno></BusiText></MsgText>";
                        try {
                            String result1 = tcpClient.sendToCsp(TextMessage, tranType.trim());// 调CSP
                            log.info("dealWithBps处理===============8");
                            log.info(result1);
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                    // 短信通知业务部门--------------------------------------
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

        } else if ("0114003".equals(tranType.trim())) {// 5.2.3批量文件重发请求
            /*
             * 1.从bps的ftp取txt到前置 2.在前置将txt压缩，同时生成md5+filename的签名（报文要用） 3.
             * 将zip上传到sb的sftp 4. 删除你本地的txt以及zip
             */
            String insType = docRecieved.getRootElement().element("GrpHdr").element("Sender").element("InstId").getText().toString().trim().substring(7, 10);
            String InstId = docRecieved.getRootElement().element("GrpHdr").element("Sender").element("InstId").getText().toString();
            String keyType = insType;// 秘钥名称
            String fileMD5 = "";
            String fileSig = "";

            String fileName = docRecieved.getRootElement().element("BusiText").element("FileName").getText().toString().trim();
            String BatchNo = docRecieved.getRootElement().element("BusiText").element("BatchNo").getText().toString().trim();
            String BankSeqNo = SiSeqNo + "104";
            String remoterPath = "";
            log.info("dealWithBps处理===============9");
            // 通知BPS系统
            messageToBps = messageToBps + BatchNo + "|" + fileName + "|";
            try {

                String result = tcpClient.sendToBps(messageToBps, "0114003");
                String[] str = result.split(",");
                String str1 = str[0];
                docGenerated.getRootElement().element("BusiText").element("Rst").element("Code").setText(str1.split("\\|", -1)[0]);
                docGenerated.getRootElement().element("BusiText").element("Rst").element("Info").setText(str1.split("\\|", -1)[1]);
                String fileSavePath = EnvConfig.getProperty("file.save.path");
                keyType = InstId.substring(0, 4) + insType;
                String paths = File.separator + "B104ToS" + keyType;
                String filePath = fileSavePath + keyType + File.separator;
                String ftpfilePath = "institution" + File.separator + insType;
                // 从bps的ftp下载回盘文件
                Ftp ftp = new Ftp(bpsIp, 21, bpsUserName, bpsUserPasswd);
                ftp.getClient().setFileType(FTP.BINARY_FILE_TYPE);
                ftp.download(ftpfilePath, fileName, FileUtil.newFile(filePath + fileName));
                ftp.close();
                // 压缩回盘文件
                if (GzUtil.doCompressFile(filePath + fileName)) {
                    log.info("压缩：" + fileName + " 完成");
                } else {
                    log.error("压缩：" + fileName + " 失败");
                }
                log.info("dealWithBps处理===============10");
                // 求压缩文件的md5
                // fileMD5 = Md5Util.getMd5(filePath + fileName + ".gz");
                // 连接sftp上传回盘文件
                String keyPath = EnvConfig.getProperty("sftpKey.save.path");
                boolean iploadFlag = SftpFileUtil.priKeyUpload(22, keyPath, "", paths, filePath, fileName);
                if (iploadFlag) {
                    log.info("上传文件：" + fileName + " 完成");
                    // 读取文件内容改为md5+文件名
                    // String filecontent = FileUtils.FileRead(filePath +
                    // fileName);

                    // 文件名签名
                    File gzFile = FileUtil.newFile(filePath + fileName + ".gz");
                    String filecontent = DigestUtil.md5Hex(FileUtils.file2byte(gzFile)) + fileName + ".gz";
                    //
                    // filecontent = fileMD5 + fileName + ".gz";
                    fileSig = RsaUtil.genValiInfo(filecontent.getBytes(AppValues.csn_U8), keyType);
                    // overSign=fileSig;
                    log.info("签名字符串：" + fileSig);
                    System.out.println("签名字符串：" + fileSig);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            docGenerated.getRootElement().element("GrpHdr").element("Rst").element("Code").setText("0000");
            docGenerated.getRootElement().element("GrpHdr").element("Rst").element("Info").setText("已处理");
            docGenerated.getRootElement().element("BusiText").element("SiSeq").setText(SiSeqNo);
            docGenerated.getRootElement().element("BusiText").element("BkSeq").setText(BankSeqNo);
            log.info("dealWithBps处理===============112");
        } else if (tranType.trim().equals("0113007")) {// 5.2.5批量结算文件处理进展查询
            String GenDate = docRecieved.getRootElement().element("GrpHdr").element("Date").getText().toString().trim();
            // 判断是否有文件名节点，有则按文件名进行查询
            if (docRecieved.selectSingleNode("//BusiText/FileName") != null) {
                String FileName = docRecieved.getRootElement().element("BusiText").element("FileName").getText().toString().trim();
                // FileName=FileName.substring(0, FileName.length()-3);
                messageToBps = messageToBps + "queryByFilename|" + FileName + "|";
                try {
                    log.info("dealWithBps处理===============12");
                    String result = tcpClient.sendToBps(messageToBps, "0113007");
                    docGenerated.getRootElement().element("GrpHdr").element("Rst").element("Code").setText("0000");
                    docGenerated.getRootElement().element("GrpHdr").element("Rst").element("Info").setText("已处理");
                    docGenerated.getRootElement().element("BusiText").element("SiSeq").setText(docRecieved.getRootElement().element("BusiText").element("SiSeq").getText().toString());
                    docGenerated.getRootElement().element("BusiText").element("BkSeq").setText(docRecieved.getRootElement().element("BusiText").element("SiSeq").getText().toString() + "104");
                    docGenerated.getRootElement().element("BusiText").element("Rst").element("Code").setText(result.split("\\|", -1)[0]);
                    docGenerated.getRootElement().element("BusiText").element("Rst").element("Info").setText(result.split("\\|", -1)[1]);
                    docGenerated.getRootElement().element("BusiText").element("LoopCount").setText("1");
                    docGenerated.getRootElement().element("BusiText").element("TotalCount").setText("1");
                    docGenerated.getRootElement().element("BusiText").element("Loop").element("FileName").setText(FileName);
                    docGenerated.getRootElement().element("BusiText").element("Loop").element("FileStatus").setText("已发放");
                    docGenerated.getRootElement().element("BusiText").element("Loop").element("FileDetail").setText(result.split("\\|", -1)[1]);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            } else {// 按日期进行查询
                log.info("dealWithBps处理===============13");
                String FetchNum = docRecieved.getRootElement().element("BusiText").element("FetchNum").getText().toString().trim();
                String BeginNum = docRecieved.getRootElement().element("BusiText").element("BeginNum").getText().toString().trim();

                Element LoopCount = docRecieved.getRootElement().element("BusiText").addElement("LoopCount");
                Element loops = docRecieved.getRootElement().element("BusiText").element("Loop");
                LoopCount.setText(FetchNum);
                Element TotalCount = docRecieved.getRootElement().element("BusiText").addElement("TotalCount");
                readEle(loops);
                for (int i = 0; i < Integer.parseInt(LoopCount.getText().toString()); i++) {
                    Element FileName = docRecieved.getRootElement().element("BusiText").addElement("FileName");
                    Element FileStatus = docRecieved.getRootElement().element("BusiText").addElement("FileStatus");
                    Element FileDetail = docRecieved.getRootElement().element("BusiText").addElement("FileDetail");
                }

                messageToBps = messageToBps + FetchNum + "|" + BeginNum + "|";
                try {
                    String result = tcpClient.sendToBps(messageToBps, "0113007");
                    docGenerated.getRootElement().element("BusiText").element("Rst").element("Code").setText(result.substring(0, 4));
                    docGenerated.getRootElement().element("BusiText").element("Rst").element("Info").setText(result.substring(4));

                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

        }
        return docGenerated;

    }

    // 处理社保请求的具体业务逻辑。跟csp相关的交易直接透传：单笔结算、单笔结算冲正、单笔结算调账，余额查询，连通性测试
    public String dealWithCsp(String docRecieved, String tranType) {
        TcpClient tcpClient = new TcpClient();
        String result = "";
        try {
            result = tcpClient.sendToCsp(docRecieved.toString(), tranType).substring(4);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    // 处理Bps请求：回盘文件就绪通知
    private Document processBpsRequest(Socket cspSocket) throws Exception {
        PrintWriter cspOut = null;
        BufferedReader cspIn = null;
        try{
            String retmessage = null;
//         String bpsUserName = GMUtil.db(key, iv, userName1);
//
//         String bpsUserPasswd = GMUtil.db(key, iv, passwd1);

            String bpsUserName = userName1;

            String bpsUserPasswd = passwd1;

            Document docGenerated = XmlUtils.generateXmlHead("0214001");
            TcpClient tcpClient = new TcpClient();
            // 取得Bps报文
            // 从socket中取得输出流，并构造PrintWriter对象，准备输出报文
            cspOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(cspSocket.getOutputStream())), true);
            // 从输入流缓冲区中读取数据
            cspIn = new BufferedReader(new InputStreamReader(cspSocket.getInputStream()));
            String bpsMessage = "";
            bpsMessage = cspIn.readLine();
            System.out.println("接收到Bps报文：" + bpsMessage);
            log.info("接收到Bps报文：{}", bpsMessage);
            if (bpsMessage.length() > 4) {// 长度判断
                // cspMessage = cspMessage.substring(4, cspMessage.length());

                String tranType = bpsMessage.substring(0, 7).toString().trim();
                if ("0214001".equals(tranType)) {// 系统连通性测试
                    // String Version = bpsMessage.split("\\|", -1)[0].trim();
                    String Reference = bpsMessage.split("\\|", -1)[1].trim();
                    String BusinessCode = bpsMessage.split("\\|", -1)[2].trim();
                    // String TradeSource = bpsMessage.split("\\|", -1)[3].trim();
                    String Sender = bpsMessage.split("\\|", -1)[3].trim();
                    String Recver = bpsMessage.split("\\|", -1)[4].trim();
                    String TransactionDate = bpsMessage.split("\\|", -1)[5].trim();
                    String TransactionTime = bpsMessage.split("\\|", -1)[6].trim();
                    // String Resend = bpsMessage.split("\\|", -1)[9].trim();
                    // String ReservedZone = bpsMessage.split("\\|", -1)[7].trim();
                    String Digest = bpsMessage.split("\\|", -1)[7].trim();
                    // String SiSeqNo = bpsMessage.split("\\|", -1)[11].trim();
                    String BkSeqNo = bpsMessage.split("\\|", -1)[8].trim();
                    String Ktype = "";
                    Ktype = Recver.substring(7, 10);
                    String keytype = "";
                    keytype = Recver.substring(0, 4) + Ktype;

                    // Document docRecieved =
                    // DocumentHelper.parseText(bpsMessage.trim());//将xml字符串转成xml
                    // docGenerated.getRootElement().element("GrpHdr").element("Version").setText(Version);
                    docGenerated.getRootElement().element("GrpHdr").element("Ref").setText(Reference);
                    docGenerated.getRootElement().element("GrpHdr").element("BusCd").setText(BusinessCode);
                    // docGenerated.getRootElement().element("GrpHdr").element("TradSrc").setText(TradeSource);
                    docGenerated.getRootElement().element("GrpHdr").element("Sender").element("InstId").setText(Sender);
                    docGenerated.getRootElement().element("GrpHdr").element("Recver").element("InstId").setText(Recver);
                    docGenerated.getRootElement().element("GrpHdr").element("Date").setText(TransactionDate);
                    docGenerated.getRootElement().element("GrpHdr").element("Time").setText(TransactionTime);
                    // docGenerated.getRootElement().element("GrpHdr").element("Resend").setText(Resend);
                    // docGenerated.getRootElement().element("GrpHdr").element("ReservedZone").setText(ReservedZone);
                    docGenerated.getRootElement().element("GrpHdr").element("Dgst").setText(Digest);
                    docGenerated.getRootElement().element("BusiText").element("BkSeq").setText(BkSeqNo);
                    docGenerated.getRootElement().element("GrpHdr").element("Rst").element("Code").setText("0001");
                    docGenerated.getRootElement().element("GrpHdr").element("Rst").element("Info").setText("待处理");
                    // 根据不同的业务功能号进行不同的处理
                    // deal(docRecieved,docGenerated,tranType);
                    // 处理完成的document转为xml报文
                    retmessage = XmlUtils.docToXml(docGenerated);
                    log.info(retmessage);
                    String overSign = RsaUtil.genValiInfo(retmessage.trim().getBytes(AppValues.csn_U8), keytype);// 对报文进行签名
                    System.out.println(overSign.getBytes(AppValues.csn_U8).length);
                    String res = tcpClient.sendToSb(docGenerated, overSign);

                    Document docRecieved = DocumentHelper.parseText(res.trim());// 将xml字符串转成xml
                    DataOutputStream dataout = new DataOutputStream(cspSocket.getOutputStream());
                    String Code = docRecieved.getRootElement().element("BusiText").element("Rst").element("Code").getText().toString();
                    String Info = docRecieved.getRootElement().element("BusiText").element("Rst").element("Info").getText().toString();
                    String resMessage = Code + Info;
                    byte[] data = resMessage.getBytes(AppValues.csn_U8);
                    if (data != null) {
                        String output = new String(data, AppValues.csn_U8);
                        log.info("返回报文为：\n" + output);
                        // System.out.println("==================返回BPS的数据为：" +
                        // output);
                        dataout.write(data, 0, data.length);
                        dataout.flush();
                    }
                    dataout.close();
                } else if ("0214002".equals(tranType)) {// 回盘文件就绪通知
                    docGenerated = XmlUtils.generateXmlHead(tranType);
                    // 交易码|养老机构编码|险种|回盘文件名|发起机构号|接收机构号|银行流水号
                    // BusinessCode
                    String insOrgCode = bpsMessage.split("\\|", -1)[1].trim();
                    String insType = bpsMessage.split("\\|", -1)[2].trim();
                    String fileName = bpsMessage.split("\\|", -1)[3].trim();
                    String recver = bpsMessage.split("\\|", -1)[4].trim();
                    String sender = bpsMessage.split("\\|", -1)[5].trim();
                    String BkSeq = bpsMessage.split("\\|", -1)[6].trim();
                    String Resend = bpsMessage.split("\\|", -1)[7].trim();
                    String fileSig = "";
                    String fileMD5 = "";
                    log.info(bpsMessage);

                    String keyType = insType;// 秘钥名称
                    String remoterPath = "/" + insType;
                    String InstId1 = "";
                    String InstId = docGenerated.getRootElement().element("GrpHdr").element("Recver").element("InstId").getText().toString();
                    if (!InstId.equals("") || InstId != "") {
                        InstId1 = InstId.substring(7, 10);
                    } else {
                        InstId1 = insOrgCode.substring(0, 4);
                    }
                    String filePath = "";
                    String fileSavePath = EnvConfig.getProperty("file.save.path");
                    keyType = recver.substring(0, 4) + insType;
                    String paths = File.separator + "B104ToS" + keyType;
                    filePath = fileSavePath + keyType + File.separator;
                    String ftpfilePath = "institution" + File.separator + insType + File.separator;
                    // 从bps的ftp下载回盘文件

                    try {
                        Ftp ftp = new Ftp(bpsIp, 21, bpsUserName, bpsUserPasswd);
                        ftp.getClient().setFileType(FTP.BINARY_FILE_TYPE);
                        ftp.download(ftpfilePath, fileName, FileUtil.newFile(filePath + fileName));
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                    // 压缩回盘文件
                    if (GzUtil.doCompressFile(filePath + fileName)) {
                        log.info("压缩：" + fileName + " 完成");
                    } else {
                        log.error("压缩：" + fileName + " 失败");
                    }
                    // 求压缩文件的md5
                    File gzFile = FileUtil.newFile(filePath + fileName + ".gz");
                    fileMD5 = DigestUtil.md5Hex(FileUtils.file2byte(gzFile));
                    log.info("md5值为：" + fileMD5);
                    // 连接sftp上传回盘文件
                    String keyPath = EnvConfig.getProperty("sftpKey.save.path");
                    boolean iploadFlag = SftpFileUtil.priKeyUpload(22, keyPath, "", paths, filePath, fileName);
                    // if(true){
                    String overSign = "";
                    if (iploadFlag) {
                        log.info("上传文件：" + fileName + " 完成");
                        // 读取文件内容改为md5+文件名
                        // String filecontent = FileUtils.FileRead(filePath +
                        // fileName);

                        // 文件名签名
                        String filecontent = fileMD5 + fileName + ".gz";
                        fileSig = RsaUtil.genValiInfo(filecontent.getBytes(AppValues.csn_U8), keyType);
                        // overSign=fileSig;
                        log.info("签名字符串：" + fileSig);
                        System.out.println("签名字符串：" + fileSig);
                        docGenerated.getRootElement().element("GrpHdr").element("Resend").setText(Resend);
                        docGenerated.getRootElement().element("BusiText").element("FileName").setText(fileName);
                        docGenerated.getRootElement().element("BusiText").element("FileSignMsg").setText(fileSig);
                        docGenerated.getRootElement().element("BusiText").element("FileMD5").setText(fileMD5);
                        docGenerated.getRootElement().element("GrpHdr").element("Sender").element("InstId").setText(sender);
                        docGenerated.getRootElement().element("GrpHdr").element("Recver").element("InstId").setText(recver);
                        docGenerated.getRootElement().element("BusiText").element("BkSeq").setText(BkSeq);
                        // 报文签名
                        retmessage = XmlUtils.docToXml(docGenerated);
                        overSign = RsaUtil.genValiInfo(retmessage.getBytes(AppValues.csn_U8), keyType);
                        retmessage = "0000接收成功！";
                    } else {
                        log.error("上传文件：" + fileName + " 失败,server退出");
                        System.out.println("上传文件：" + fileName + " 失败,server退出");
                        retmessage = "9999上传sftp失败！";
                        log.error("返回BPS的报文为：" + retmessage);
                    }
                    DataOutputStream dataout = new DataOutputStream(cspSocket.getOutputStream());
                    String result2 = tcpClient.sendToSb(docGenerated, overSign);
                    String Code = "";
                    String Info = "";
                    if (!result2.equals("null|与社保通信失败")) {
                        Document docRecieved = DocumentHelper.parseText(result2.trim());// 将xml字符串转成xml
                        Code = docRecieved.getRootElement().element("BusiText").element("Rst").element("Code").getText().toString();
                        Info = docRecieved.getRootElement().element("BusiText").element("Rst").element("Info").getText().toString();
                    } else {
                        Code = "null";
                        Info = "报文为空";
                    }
                    String resMessage = Code + "|" + Info;
                    byte[] data = resMessage.getBytes(AppValues.csn_U8);
                    if (data != null) {
                        String output = new String(data, AppValues.csn_U8);
                        log.info("返回报文为：\n" + output);
                        System.out.println("返回报文为：\n" + output);
                        System.out.println("==================返回BPS的数据为：" + output);
                        dataout.write(data, 0, data.length);
                        dataout.flush();
                    }
                    dataout.close();
                    cspOut.write(retmessage + "\r\n");// 给bps返回数据
                    cspOut.flush();
                }
            }


            return docGenerated;
        }catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }finally {
            try{
                if(cspIn != null) {
                    cspIn.close();
                }
            }catch (Exception e) {
                log.error("关闭BufferedReader异常");
            }

            try{
                if(cspOut != null) {
                    cspOut.close();
                }
            }catch (Exception e) {
                log.error("关闭PrintWriter异常");
            }

            try{
                if(cspSocket != null) {
                    cspSocket.close();
                }
            }catch (Exception e) {
                log.error("关闭cspSocket异常");
            }
        }

    }

    // 处理Csp请求：日终文件通知0224001、收支文件通知0222002、中银E贷社保0200002、中银E贷授权码0200003
    public void processCspRequest(Socket cspSocket) throws Exception {
        log.info("=====JM===");
        log.info("key:{}", key);
        log.info("iv:{}", iv);
        log.info("userName1:{}", userName1);
        log.info("passwd1:{}", passwd1);
         String bpsUserName = userName1;

         String bpsUserPasswd =  passwd1;
        InputStream inp = null;
        BufferedReader isr = null;
        BufferedReader bfr = null;
        OutputStream ots = null;
        String info = "";
        TcpClient tcpClient = new TcpClient();
        try {

            inp = cspSocket.getInputStream();
            ots = cspSocket.getOutputStream();
            isr = IoUtil.getReader(inp, "GBK");
            bfr = IoUtil.getReader(isr);
            info = bfr.readLine();
            String in = info;
            System.out.println("接收csp报文：" + in);
            String cspMessage = in;// new String(recBuffer,AppValues.csn_U8);
            // 去掉前4位报文长度获取实际报文内容
            cspMessage = cspMessage.substring(4);
            log.info("报文数据{}", cspMessage);
            // 长度判断
            if (cspMessage.length() > 4) {
                String resMessage = "";
                String tranType = cspMessage.split("\\|", -1)[0].trim();
                if (tranType.equals("0214002")) {                                    //之前的代码
                    String tranDate = cspMessage.split("\\|", -1)[1].trim();
                    String insOrgCode = cspMessage.split("\\|", -1)[2].trim();
                    String insType = cspMessage.split("\\|", -1)[3].trim();
                    String fileName = cspMessage.split("\\|", -1)[4].trim();
                    String recver = cspMessage.split("\\|", -1)[5].trim();
                    String sender = cspMessage.split("\\|", -1)[6].trim();
                    String BkSeq = cspMessage.split("\\|", -1)[7].trim();
                    String Resend = cspMessage.split("\\|", -1)[8].trim();
                    String fileSig = "";
                    String fileMD5 = "";
                    log.info(cspMessage);

                    String keyType = insType;// 秘钥名称

                    String filePath = "";
                    String retmessage = "";// 发送社保的最终报文

                    keyType = recver.substring(0, 4) + insType;


                    String paths = File.separator +  "B104ToS" + keyType;

                    // 加强文件名校验 - 修复路径遍历漏洞
                   /* if (!FileSecurityUtil.validateFileName(fileName)) {
                        log.error("不安全的文件名: {}", fileName);
                        // 返回错误响应
                        if (ots != null) {
                            String errorResponse = "9999文件名安全验证失败";
                            byte[] errorData = errorResponse.getBytes("GBK");
                            ots.write(errorData);
                        }
                        return;
                    }

                    String safeFileName = FileSecurityUtil.getSecureFileName(fileName);
                    if (safeFileName == null) {
                        log.error("无法获取安全文件名: {}", fileName);
                        if (ots != null) {
                            String errorResponse = "9999文件名安全处理失败";
                            byte[] errorData = errorResponse.getBytes("GBK");
                            ots.write(errorData);
                        }
                        return;
                    }

                    // 验证本地路径安全性
                    if (!FileSecurityUtil.validateFilePath(paths)) {
                        log.error("不安全的本地路径: {}", paths);
                        if (ots != null) {
                            String errorResponse = "9999本地路径安全验证失败";
                            byte[] errorData = errorResponse.getBytes("GBK");
                            ots.write(errorData);
                        }
                        return;
                    }*/
                    String dzFileSavePath = EnvConfig.getProperty("dz.file.save.path");
                    //filePath = AppValues.DZfile_save_path + "" + "\\";
                    filePath = dzFileSavePath + "" + insType + File.separator;
                    //ftpfilePath = "institution\\" + insType + "\\";
                    //测试用
                    String ftpfilePath = "sbdz" + File.separator+"account" + File.separator + insType;

                    // 从bps的ftp下载回盘文件
                    try {
                        Ftp ftp = new Ftp(bpsIp, 21, bpsUserName, bpsUserPasswd);
                        ftp.getClient().setFileType(FTP.BINARY_FILE_TYPE);
                        ftp.download(ftpfilePath, fileName, FileUtil.newFile(filePath + fileName));
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }

                    // 0224001日终交易核对流水、0222002社保机构账户收支明细就绪通知，按交易码组基础报文
                    Document docGenerated = XmlUtils.generateXmlHead(tranType);

                    // 压缩回盘文件
                    if (GzUtil.doCompressFile(filePath + fileName)) {
                        log.info("压缩：" + fileName + " 完成");
                    } else {
                        log.error("压缩：" + fileName + " 失败");
                    }
                    // 求压缩文件的md5
                    File gzFile = FileUtil.newFile(filePath + fileName + ".gz");
                    fileMD5 = DigestUtil.md5Hex(FileUtils.file2byte(gzFile));
                    log.info("md5值为：" + fileMD5);
                    // 连接sftp上传回盘文件
                    String keyPath = EnvConfig.getProperty("sftpKey.save.path");
                    boolean iploadFlag = SftpFileUtil.priKeyUpload(22, keyPath, "", paths, filePath, fileName);
                    // if(true){
                    String overSign = "";
                    if (iploadFlag) {
                        log.info("上传文件：" + fileName + " 完成");

                        // 文件名签名
                        String filecontent = fileMD5 + fileName + ".gz";
                        fileSig = RsaUtil.genValiInfo(filecontent.getBytes(AppValues.csn_U8), keyType);
                        log.info("签名字符串：" + fileSig);
                        System.out.println("签名字符串：" + fileSig);
                        // 报文要素赋值
                        docGenerated.getRootElement().element("GrpHdr").element("Resend").setText(Resend);
                        docGenerated.getRootElement().element("BusiText").element("FileName").setText(fileName);
                        docGenerated.getRootElement().element("BusiText").element("FileSignMsg").setText(fileSig);
                        docGenerated.getRootElement().element("BusiText").element("FileMD5").setText(fileMD5);
                        docGenerated.getRootElement().element("GrpHdr").element("Sender").element("InstId").setText(sender);
                        docGenerated.getRootElement().element("GrpHdr").element("Recver").element("InstId").setText(recver);
                        docGenerated.getRootElement().element("BusiText").element("BkSeq").setText(BkSeq);
                        // 报文签名
                        retmessage = XmlUtils.docToXml(docGenerated);
                        overSign = RsaUtil.genValiInfo(retmessage.getBytes(AppValues.csn_U8), keyType);
                        retmessage = "0000发送成功！";
                    } else {
                        log.error("上传文件：" + fileName + " 失败,server退出");
                        System.out.println("上传文件：" + fileName + " 失败,server退出");
                        retmessage = "9999上传sftp失败！";
                        log.error("返回CSP的报文为：" + retmessage);
                    }
                    DataOutputStream dataout = new DataOutputStream(cspSocket.getOutputStream());
                    String result2 = tcpClient.sendToSb(docGenerated, overSign);
                    String Code = "";
                    String Info = "";
                    if (!result2.equals("null|与社保通信失败")) {
                        Document docRecieved = DocumentHelper.parseText(result2.trim());// 将xml字符串转成xml
                        Code = docRecieved.getRootElement().element("BusiText").element("Rst").element("Code").getText().toString();
                        Info = docRecieved.getRootElement().element("BusiText").element("Rst").element("Info").getText().toString();
                    } else {
                        Code = "null";
                        Info = "报文为空";
                    }
                    resMessage = Code + "|" + Info + "\r\n";
                    byte[] data = resMessage.getBytes(AppValues.csn_GB);
                    if (data != null) {
                        String output = new String(data, AppValues.csn_GB);
                        System.out.println("=============" + output.length());
                        log.info("返回报文为：\n" + output);
                        System.out.println("返回报文为：\n" + output);
                        ots.write(data);
                    }
                } else if (tranType.equals("0200002")) {//中银E贷社保
//					
                    String sbXML1 = cspMessage.split("\\|", -1)[1].trim();//总行请求社保险种A 的报文110
                    String sbXML2 = cspMessage.split("\\|", -1)[2].trim();//总行请求社保险种B 的报文120
                    String headXml = cspMessage.split("\\|", -1)[3].trim();//总行请求社保险种B 的报文
                    Document docGenerated1 = DocumentHelper.parseText(sbXML1);
                    String sbXML1temp = XmlUtils.docToXml(docGenerated1);
                    sbXML1 = XmlUtils.replaceBlank(sbXML1temp);
                    String keyType1 = "1400110";//docGenerated1.getRootElement().element("BusiText").element("Aae140").getText().toString();
                    String overSign = RsaUtil.genValiInfo(sbXML1.getBytes(AppValues.csn_U8), keyType1);// 对报文进行签名
                    String result1 = tcpClient.sendToSbE(docGenerated1, overSign);
                    //String result1 = "<MsgText><GrpHdr><Version>1.0.0</Version><Ref>1021000000002012090600000000000000000001</Ref><BusCd>0200002</BusCd><TradSrc>B</TradSrc><Sender><InstId>1400000110</InstId></Sender><Recver><InstId>104000000001</InstId></Recver><Resend>N</Resend><Date>20230208</Date><Time>093610</Time><Dgst>养老信息查询</Dgst><Rst><Code>0000</Code><Info>已处理</Info></Rst></GrpHdr><BusiText><Rst><Code>0000</Code><Info>交易成功</Info></Rst><Aae140>110</Aae140><BkSeq>000000000000000000</BkSeq><SiSeq>202302080000000115</SiSeq><Aac002>14272419970214001X</Aac002><Aac003>田川</Aac003><Aac004>2</Aac004><Aac005>01</Aac005><Aac006>19700219</Aac006><Aab301>140699</Aab301><Aac009>11</Aac009><Aac010>朔州市平鲁区向阳堡乡派出所</Aac010><Aac058>01</Aac058><Aac147>14272419970214001X</Aac147><Aae005>null</Aae005><Aac067>13834422428</Aac067><Aae006>山西省朔州市朔城区府南小区</Aae006><Aae007>036000</Aae007><Aac191>null</Aac191><Bac504>null</Bac504><Aac008>1</Aac008><Aac031>1</Aac031><Aac084>0</Aac084><Aab001>110000000006443</Aab001><Aab004>中煤财产保险股份有限公司朔州中心支公司</Aab004><Aab998>null</Aab998><Aab021>40</Aab021><Aab019>10</Aab019><Aab020>151</Aab020><Aab022>J6610</Aab022><Aab023>中煤财产保险股份有限公司朔州中心支公司</Aab023><Aaa120>1</Aaa120><Aab051>1</Aab051><Aac032>200909</Aac032><Aae030>20090901</Aae030><Aae031>null</Aae031><Aae041>200909</Aae041><Aae042>202212</Aae042><Aae003>202212</Aae003><Aac040>20210424</Aac040><Aae180>20211941</Aae180><Aae200>20</Aae200><Aae201>153</Aae201><Aae082>20210722</Aae082><Aab127>27957.4</Aab127><Aic268>20244229</Aic268><Aac104>20211001</Aac104><Aae760>null</Aae760><LoopCount>20</LoopCount><TotalCount>1</TotalCount><Loops><Loop><Aae003>202212</Aae003><Aae004>202212</Aae004><Aaa115>10</Aaa115><Aae020>20211470</Aae020><Aae022>20210722</Aae022><Aae002>202212</Aae002><Aae080>20211470</Aae080><Aae082>20210722</Aae082><Aae058>20211306</Aae058><Aab120>20211941</Aab120><Aab121>20211941</Aab121><Aab101>3548</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202211</Aae003><Aae004>202211</Aae004><Aaa115>10</Aaa115><Aae020>20211470</Aae020><Aae022>20210722</Aae022><Aae002>202212</Aae002><Aae080>20211470</Aae080><Aae082>20210722</Aae082><Aae058>20211306</Aae058><Aab120>20211941</Aab120><Aab121>20211941</Aab121><Aab101>3548</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202210</Aae003><Aae004>202210</Aae004><Aaa115>10</Aaa115><Aae020>20211470</Aae020><Aae022>20210722</Aae022><Aae002>202211</Aae002><Aae080>20211470</Aae080><Aae082>20210722</Aae082><Aae058>20211306</Aae058><Aab120>20211941</Aab120><Aab121>20211941</Aab121><Aab101>3548</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202209</Aae003><Aae004>202209</Aae004><Aaa115>10</Aaa115><Aae020>20211470</Aae020><Aae022>20210722</Aae022><Aae002>202211</Aae002><Aae080>20211470</Aae080><Aae082>20210722</Aae082><Aae058>20211306</Aae058><Aab120>20211941</Aab120><Aab121>20211941</Aab121><Aab101>3548</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202208</Aae003><Aae004>202208</Aae004><Aaa115>10</Aaa115><Aae020>20211470</Aae020><Aae022>20210722</Aae022><Aae002>202211</Aae002><Aae080>20211470</Aae080><Aae082>20210722</Aae082><Aae058>20211306</Aae058><Aab120>20211941</Aab120><Aab121>20211941</Aab121><Aab101>3548</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202207</Aae003><Aae004>202207</Aae004><Aaa115>10</Aaa115><Aae020>20211001</Aae020><Aae022>20210722</Aae022><Aae002>202211</Aae002><Aae080>20211001</Aae080><Aae082>20210722</Aae082><Aae058>20210722</Aae058><Aab120>20211941</Aab120><Aab121>20211941</Aab121><Aab101>3548</Aab101><Aaa041>0.08</Aaa041><Aaa042>0</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202207</Aae003><Aae004>202207</Aae004><Aaa115>10</Aaa115><Aae020>20211001</Aae020><Aae022>20211001</Aae022><Aae002>202211</Aae002><Aae080>20211001</Aae080><Aae082>20211001</Aae082><Aae058>20211001</Aae058><Aab120>20211001</Aab120><Aab121>20211001</Aab121><Aab101>3548</Aab101><Aaa041>0</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202206</Aae003><Aae004>202206</Aae004><Aaa115>10</Aaa115><Aae020>20211001</Aae020><Aae022>20210747</Aae022><Aae002>202211</Aae002><Aae080>20211001</Aae080><Aae082>20210747</Aae082><Aae058>20210747</Aae058><Aab120>20212122</Aab120><Aab121>20212122</Aab121><Aab101>3548</Aab101><Aaa041>0.08</Aaa041><Aaa042>0</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202206</Aae003><Aae004>202206</Aae004><Aaa115>10</Aaa115><Aae020>20211001</Aae020><Aae022>20211001</Aae022><Aae002>202211</Aae002><Aae080>20211001</Aae080><Aae082>20211001</Aae082><Aae058>20211001</Aae058><Aab120>20211001</Aab120><Aab121>20211001</Aab121><Aab101>3548</Aab101><Aaa041>0</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202205</Aae003><Aae004>202205</Aae004><Aaa115>10</Aaa115><Aae020>20211001</Aae020><Aae022>20210747</Aae022><Aae002>202211</Aae002><Aae080>20211001</Aae080><Aae082>20210747</Aae082><Aae058>20210747</Aae058><Aab120>20212122</Aab120><Aab121>20212122</Aab121><Aab101>3548</Aab101><Aaa041>0.08</Aaa041><Aaa042>0</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202205</Aae003><Aae004>202205</Aae004><Aaa115>10</Aaa115><Aae020>20211001</Aae020><Aae022>20211001</Aae022><Aae002>202211</Aae002><Aae080>20211001</Aae080><Aae082>20211001</Aae082><Aae058>20211001</Aae058><Aab120>20211001</Aab120><Aab121>20211001</Aab121><Aab101>3548</Aab101><Aaa041>0</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202204</Aae003><Aae004>202204</Aae004><Aaa115>10</Aaa115><Aae020>20211516</Aae020><Aae022>20210747</Aae022><Aae002>202211</Aae002><Aae080>20211516</Aae080><Aae082>20210747</Aae082><Aae058>20211249</Aae058><Aab120>20212122</Aab120><Aab121>20212122</Aab121><Aab101>3548</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202203</Aae003><Aae004>202203</Aae004><Aaa115>10</Aaa115><Aae020>20211516</Aae020><Aae022>20210747</Aae022><Aae002>202211</Aae002><Aae080>20211516</Aae080><Aae082>20210747</Aae082><Aae058>20211249</Aae058><Aab120>20212122</Aab120><Aab121>20212122</Aab121><Aab101>3548</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202202</Aae003><Aae004>202202</Aae004><Aaa115>10</Aaa115><Aae020>20211516</Aae020><Aae022>20210747</Aae022><Aae002>202211</Aae002><Aae080>20211516</Aae080><Aae082>20210747</Aae082><Aae058>20211249</Aae058><Aab120>20212122</Aab120><Aab121>20212122</Aab121><Aab101>3548</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202201</Aae003><Aae004>202201</Aae004><Aaa115>10</Aaa115><Aae020>20211516</Aae020><Aae022>20210747</Aae022><Aae002>202211</Aae002><Aae080>20211516</Aae080><Aae082>20210747</Aae082><Aae058>20211249</Aae058><Aab120>20212122</Aab120><Aab121>20212122</Aab121><Aab101>3548</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202106</Aae003><Aae004>202106</Aae004><Aaa115>10</Aaa115><Aae020>20211516</Aae020><Aae022>20210747</Aae022><Aae002>202107</Aae002><Aae080>20211516</Aae080><Aae082>20210747</Aae082><Aae058>20211249</Aae058><Aab120>20212122</Aab120><Aab121>20212122</Aab121><Aab101>3235</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202105</Aae003><Aae004>202105</Aae004><Aaa115>10</Aaa115><Aae020>20210831</Aae020><Aae022>20211170</Aae022><Aae002>202107</Aae002><Aae080>20210831</Aae080><Aae082>20211170</Aae082><Aae058>20211624</Aae058><Aab120>20213642</Aab120><Aab121>20213642</Aab121><Aab101>3235</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202104</Aae003><Aae004>202104</Aae004><Aaa115>10</Aaa115><Aae020>20210831</Aae020><Aae022>20211170</Aae022><Aae002>202107</Aae002><Aae080>20210831</Aae080><Aae082>20211170</Aae082><Aae058>20211624</Aae058><Aab120>20213642</Aab120><Aab121>20213642</Aab121><Aab101>3235</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202103</Aae003><Aae004>202103</Aae004><Aaa115>10</Aaa115><Aae020>20210831</Aae020><Aae022>20211170</Aae022><Aae002>202107</Aae002><Aae080>20210831</Aae080><Aae082>20211170</Aae082><Aae058>20211624</Aae058><Aab120>20213642</Aab120><Aab121>20213642</Aab121><Aab101>3235</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop><Loop><Aae003>202102</Aae003><Aae004>202102</Aae004><Aaa115>10</Aaa115><Aae020>20210831</Aae020><Aae022>20211170</Aae022><Aae002>202107</Aae002><Aae080>20210831</Aae080><Aae082>20211170</Aae082><Aae058>20211624</Aae058><Aab120>20213642</Aab120><Aab121>20213642</Aab121><Aab101>3235</Aab101><Aaa041>0.08</Aaa041><Aaa042>0.16</Aaa042><Aae078>1</Aae078></Loop></Loops></BusiText></MsgText>";
                    Document docRecieved1 = null;
                    String Code1 = "";
                    System.out.println("接收社保110" + result1);

                    Document docGenerated2 = DocumentHelper.parseText(sbXML2);
                    System.out.println("原来的" + sbXML2);
                    String sbXML2temp = XmlUtils.docToXml(docGenerated2);
                    sbXML2 = XmlUtils.replaceBlank(sbXML2temp);
                    System.out.println("更改后的的" + sbXML2);
                    String keyType2 = "1400120";
                    overSign = RsaUtil.genValiInfo(sbXML2.getBytes(AppValues.csn_U8), keyType2);// 对报文进行签名
                    System.out.println(overSign);
                    String result2 = tcpClient.sendToSbE(docGenerated2, overSign);
                    //String result2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><MsgText><GrpHdr><Version>1.0.0</Version><Ref>1021000000002012090600000000000000000001</Ref><BusCd>0200002</BusCd><TradSrc>S</TradSrc><Sender><InstId>1400000120</InstId></Sender><Recver><InstId>104000000001</InstId></Recver><Resend>N</Resend><Date>20230208</Date><Time>34571</Time><Dgst>N</Dgst><Rst><Code>2001</Code><Info>交易失败未查询到人员信息。</Info></Rst></GrpHdr><BusiText><Rst><Code>2001</Code><Info>交易失败未查询到人员信息。</Info></Rst><BkSeq>000000000000000000</BkSeq><SiSeq></SiSeq><Aae140></Aae140><Aac002></Aac002><Aac003></Aac003><Aac004></Aac004><Aac006></Aac006><Aac005></Aac005><Aab301></Aab301><Aac009></Aac009><Aac010></Aac010><Aac058></Aac058><Aac147></Aac147><Aae005></Aae005><Aac067></Aac067><Aae006></Aae006><Aae007></Aae007><Aac191></Aac191><Bac504></Bac504><Aac008></Aac008><Aac031></Aac031><Aac084></Aac084><Aab001></Aab001><Aab004></Aab004><Aab998></Aab998><Aab021></Aab021><Aab019></Aab019><Aab020></Aab020><Aab022></Aab022><Aab023></Aab023><Aaa120></Aaa120><Aab051></Aab051><Aac032></Aac032><Aae030></Aae030><Aae031></Aae031><Aae041></Aae041><Aae042></Aae042><Aae003></Aae003><Aac040></Aac040><Aae180></Aae180><Aae200></Aae200><Aae201></Aae201><Aae082></Aae082><Aab127></Aab127><Aic268></Aic268><Aac104></Aac104><Aae760></Aae760><LoopCount></LoopCount><TotalCount></TotalCount><Loops></Loops></BusiText></MsgText>";
                    System.out.println("接收社保120" + result2);
                    Document docRecieved2 = null;
                    String Code2 = "";
                    if (!result1.equals("null")) {
                        docRecieved1 = DocumentHelper.parseText(result1.trim());// 将xml字符串转成xml
                        Code1 = docRecieved1.getRootElement().element("BusiText").element("Rst").element("Code").getText().toString();
                    }
                    if (!result2.equals("null")) {
                        docRecieved2 = DocumentHelper.parseText(result2.trim());// 将xml字符串转成xml
                        Code2 = docRecieved2.getRootElement().element("BusiText").element("Rst").element("Code").getText().toString();
                    }
                    JieXiMes jiexi = new JieXiMes();
                    if (Code1.equals("") || !Code1.equals("0000")) {
                        if (Code2.equals("") || !Code2.equals("0000")) {
                            resMessage = "<?xml version=\"1.0\" encoding=\"GBK\"?><CSPA05>" + headXml + "<REP_MSG><Result>5319001</Result><INF>分行查询公积金、社保、地税、国税信息无结果</INF></REP_MSG></CSPA05>";
                        } else {
                            result1 = "null";
                            resMessage = jiexi.deal(result1, result2, headXml);//110null或者失败
                        }
                    } else {
                        if (Code2.equals("") || !Code2.equals("0000")) {
                            result2 = "null";
                            resMessage = jiexi.deal(result1, result2, headXml);//120null
                        } else {
                            resMessage = jiexi.deal(result1, result2, headXml);
                        }
                    }
                    int len = StringUtil.getbyteLength(resMessage);
                    String meslen = StringUtil.lpadString(len + "", 4, "0");
                    resMessage = meslen + resMessage;
                    byte[] data = resMessage.getBytes(AppValues.csn_GB);
                    if (data != null) {
                        String output = new String(data, AppValues.csn_GB);
                        System.out.println("=============" + output.length());
                        log.info("返回报文为：\n" + output);
                        System.out.println("返回报文为：\n" + output);
                        ots.write(data);
                    }

                } else if (tranType.equals("0200003")) {//中银E贷授权码查询
                    String sbXML3 = cspMessage.split("\\|", -1)[1].trim();//总行请求社保险种A 的报文110
                    String sbXML4 = cspMessage.split("\\|", -1)[2].trim();//总行请求社保险种B 的报文120
                    String headXml = cspMessage.split("\\|", -1)[3].trim();//总行请求社保险种B 的报文
                    //110
                    Document docGenerated3 = DocumentHelper.parseText(sbXML3);
                    String sbXML3temp = XmlUtils.docToXml(docGenerated3);
                    sbXML3 = XmlUtils.replaceBlank(sbXML3temp);
                    String keyType1 = "1400110";//docGenerated1.getRootElement().element("BusiText").element("Aae140").getText().toString();
                    String overSign = RsaUtil.genValiInfo(sbXML3.getBytes(AppValues.csn_U8), keyType1);// 对报文进行签名
                    String result1 = tcpClient.sendToSbE(docGenerated3, overSign);
                    //String result1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><MsgText><GrpHdr><Version>1.0.0</Version><Ref>1021000000002012090600000000000000000001</Ref><BusCd>0214001</BusCd><TradSrc>S</TradSrc><Sender><InstId>10200000</InstId></Sender><Recver><InstId>00000001</InstId></Recver><Resend>N</Resend><Date>20130916</Date><Time>100900</Time><Dgst>个人授权协议</Dgst><Rst><Code>0000</Code><Info>已处理</Info></Rst></GrpHdr><BusiText><Rst><Code>0000</Code><Info>交易成功</Info></Rst><BkSeq>20120814100000008443</BkSeq><SiSeq>12345678901234567890</SiSeq><Authcode>NsK27QJBYnPom3NGdbYyLOoVH2flRt</Authcode></BusiText></MsgText>";
                    Document docRecieved3 = null;
                    String Code1 = "";
                    System.out.println("接收社保授权码返回110" + result1);
                    //120
                    Document docGenerated4 = DocumentHelper.parseText(sbXML4);
                    System.out.println("原来的" + sbXML4);
                    String sbXML4temp = XmlUtils.docToXml(docGenerated4);
                    sbXML4 = XmlUtils.replaceBlank(sbXML4temp);
                    System.out.println("更改后的的" + sbXML4);
                    String keyType2 = "1400120";
                    overSign = RsaUtil.genValiInfo(sbXML4.getBytes(AppValues.csn_U8), keyType2);// 对报文进行签名
                    System.out.println(overSign);
                    String result2 = tcpClient.sendToSbE(docGenerated4, overSign);
                    //String result2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><MsgText><GrpHdr><Version>1.0.0</Version><Ref>1021000000002012090600000000000000000001</Ref><BusCd>0214001</BusCd><TradSrc>S</TradSrc><Sender><InstId>10200000</InstId></Sender><Recver><InstId>00000001</InstId></Recver><Resend>N</Resend><Date>20130916</Date><Time>100900</Time><Dgst>个人授权协议</Dgst><Rst><Code>0000</Code><Info>已处理</Info></Rst></GrpHdr><BusiText><Rst><Code>0000</Code><Info>交易成功</Info></Rst><BkSeq>20120814100000008443</BkSeq><SiSeq>12345678901234567890</SiSeq><Authcode>NsK27QJBYnPom3NGdbYyLOoVH2flRR</Authcode></BusiText></MsgText>";
                    System.out.println("接收社保授权码120" + result2);
                    Document docRecieved4 = null;
                    String Code2 = "";

                    if (!result1.equals("null")) {
                        docRecieved3 = DocumentHelper.parseText(result1.trim());// 将xml字符串转成xml
                        Code1 = docRecieved3.getRootElement().element("BusiText").element("Rst").element("Code").getText().toString();
                    }
                    if (!result2.equals("null")) {
                        docRecieved4 = DocumentHelper.parseText(result2.trim());// 将xml字符串转成xml
                        Code2 = docRecieved4.getRootElement().element("BusiText").element("Rst").element("Code").getText().toString();
                    }

                    if (Code1.equals("") || !Code1.equals("0000")) {
                        if (Code2.equals("") || !Code2.equals("0000")) {
                            resMessage = "<?xml version=\"1.0\" encoding=\"GBK\"?><CSPA05>" + headXml + "<REP_MSG><Result>5319001</Result><INF>分行查询公积金、社保、地税、国税信息无结果</INF></REP_MSG></CSPA05>";
                        } else {
                            result1 = "null";//110null或者失败
                            resMessage = result1 + "|" + result2 + "|";
                        }
                    } else {
                        if (Code2.equals("") || !Code2.equals("0000")) {
                            result2 = "null";//120null或者失败
                            resMessage = result1 + "|" + result2 + "|";
                        } else {
                            resMessage = result1 + "|" + result2 + "|";
                        }
                    }

//					resMessage = result1 + "|" + result2 + "|";
                    int len = StringUtil.getbyteLength(resMessage);
                    String meslen = StringUtil.lpadString(len + "", 4, "0");
                    resMessage = meslen + resMessage;
                    byte[] data = resMessage.getBytes(AppValues.csn_GB);
                    if (data != null) {
                        String output = new String(data, AppValues.csn_GB);
                        log.info("=============" + output.length());
                        log.info("返回报文为：\n" + output);
                        ots.write(data);
                    }
                }

                ots.close();
                cspSocket.close();
            }


        } catch (Exception e) {
            log.error("程序异常错误：{}", String.valueOf(e));
        } finally {
            if (ots != null) {
                ots.close();
            }
            if (cspSocket != null) {
                cspSocket.close();
            }
        }
    }

    public void readEle(Element loops) {
        if (loops.hasMixedContent()) {
            System.out.println("节点名" + loops.getName());
            Iterator it = loops.elementIterator();
            while (it.hasNext()) {
                Element arrName = (Element) it.next();
                readEle(arrName);
            }
        } else {
            log.info("节点名{}节点值:{}", loops.getName(), loops.getTextTrim());
        }
    }

}